package org.collector.baseoper;

import java.util.HashMap;
import java.util.Random;
import java.util.Vector;

import org.apache.http.client.HttpClient;
import org.collector.data.controllerdata.SiteOfProxyStatu;
import org.collector.data.iodata.IUrl;
import org.collector.util.HttpClientTools;

public class HttpClientStatu {
	private HashMap<String,SiteOfProxyStatu> clientStatu;
	public HttpClientStatu(){
		clientStatu = new HashMap<String,SiteOfProxyStatu>();
	}
	public int getTaskQueueLength(){
		int queueLength= 0;
		synchronized(clientStatu){
			for(SiteOfProxyStatu s: clientStatu.values())
				queueLength += s.getQueuelength();
		}
		return queueLength;
	}
	public SiteOfProxyStatu getSiteOfProxyStatu(String url){
		SiteOfProxyStatu statu = null;
		synchronized(clientStatu){
			statu = clientStatu.get(url);
			if(statu == null){
				statu = new SiteOfProxyStatu();
				clientStatu.put(url, statu);
			}
		}
		return statu;
	}
	public boolean addTask(IUrl url){
		String strUrl = HttpClientTools.determineTarget(url.getUrl());
		SiteOfProxyStatu statu = null;
		synchronized(clientStatu){
			statu = clientStatu.get(strUrl);
			if(statu == null){
				statu = new SiteOfProxyStatu();
				clientStatu.put(strUrl, statu);
			}
		}
		if(statu != null){
			synchronized(statu){
				return statu.addTask(url);
			}
		}
		return false;
	}
	public boolean execute(HttpClient client){
		SiteOfProxyStatu statu = null;
		synchronized(clientStatu){
			if(clientStatu.keySet().size() == 0)
				return false;
			Vector<String> vct = new Vector<String>();
			for(String s: clientStatu.keySet())
				vct.add(s);
			int index = new Random(System.currentTimeMillis()).nextInt(vct.size());
			boolean firsttime = true;
			int i= 0;
			for(i = index;firsttime || i != index;i = (i + 1)%vct.size()){
				firsttime = false;
				if(clientStatu.get(vct.get(i)).getQueuelength() != 0)
					break;
			}
			statu = clientStatu.get(vct.get(i));
		}
		if(statu != null){
			return statu.execute(client);
		}
		return false;
	}
}
